package com.hongpu.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongpu.domain.CoolTowerEmployee;
import com.hongpu.domain.CoolTowerEmployeeSalaryProjectRelationship;
import com.hongpu.domain.CoolTowerProjectAttendance;
import com.hongpu.dto.CoolTowerProjectAttendanceDto;
import com.hongpu.dto.CoolTowerProjectAttendanceInfoDto;
import com.hongpu.dto.CoolTowerProjectAttendancePageDto;
import com.hongpu.dto.CoolTowerProjectDto;
import com.hongpu.enums.NumberOfJobsEnum;
import com.hongpu.mapper.CoolTowerProjectAttendanceMapper;
import com.hongpu.service.CoolTowerEmployeeSalaryProjectRelationshipService;
import com.hongpu.service.CoolTowerEmployeeService;
import com.hongpu.service.CoolTowerProjectAttendanceService;
import com.hongpu.utils.ResultDto;
import com.hongpu.vo.CostStatisticsVo;
import com.hongpu.vo.SelectOptionVo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Michael zhang
 * @description 针对表【cool_tower_project_attendance(冷却塔安装人员考勤打卡)】的数据库操作Service实现
 * @createDate 2025-06-10 15:50:48
 */
@Service
public class CoolTowerProjectAttendanceServiceImpl extends ServiceImpl<CoolTowerProjectAttendanceMapper, CoolTowerProjectAttendance>
        implements CoolTowerProjectAttendanceService {

    @Autowired
    CoolTowerProjectAttendanceMapper baseMapper;
    @Autowired
    CoolTowerEmployeeSalaryProjectRelationshipService coolTowerEmployeeSalaryProjectRelationshipService;
    @Autowired
    CoolTowerEmployeeService coolTowerEmployeeService;

    /**
     * 统计汇总员工在一个项目上的工数及各种费用
     *
     * @param cool_tower_project_id
     * @param cool_tower_employee_id
     */
    @Override
    public CoolTowerProjectAttendanceDto selectSum(Long cool_tower_project_id, Long cool_tower_employee_id, String startDate, String endDate) {
        try {
            return baseMapper.selectSum(cool_tower_project_id, cool_tower_employee_id, startDate, endDate);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 统计员工在项目上的打卡记录
     *
     * @param coolTowerProjectId
     * @param coolTowerEmployeeId
     * @param startDate
     * @param endDate
     */
    @Override
    public List<String> selectCheckInDate(Long coolTowerProjectId, Long coolTowerEmployeeId, String startDate, String endDate) {
        try {
            return baseMapper.selectCheckInDate(coolTowerProjectId, coolTowerEmployeeId, startDate, endDate);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 统计员工在项目上的打卡记录
     *
     * @param coolTowerProjectId
     * @param coolTowerEmployeeId
     * @param startDate
     * @param endDate
     */
    @Override
    public List<String> selectRemark(Long coolTowerProjectId, Long coolTowerEmployeeId, String startDate, String endDate) {
        try {
            return baseMapper.selectRemark(coolTowerProjectId, coolTowerEmployeeId, startDate, endDate);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据项目ID统计该项目所有的当日费用
     *
     * @param coolTowerProjectId
     * @param date
     */
    @Override
    public BigDecimal selectTotalCostByCoolTowerProjectId(Long coolTowerProjectId) {
        try {
            return baseMapper.selectTotalCostByCoolTowerProjectId(coolTowerProjectId);
        } catch (Exception e) {
            e.printStackTrace();
            return BigDecimal.ZERO;
        }
    }

    /**
     * 工数下拉列表
     */
    @Override
    public ResultDto optionList() {
        try {
            List<SelectOptionVo<Double>> result = new ArrayList<>();
            NumberOfJobsEnum[] numberOfJobsEnums = NumberOfJobsEnum.values();
            for (NumberOfJobsEnum numberOfJobsEnum : numberOfJobsEnums) {
                SelectOptionVo<Double> selectOptionVo = new SelectOptionVo<>();
                selectOptionVo.setLabel(numberOfJobsEnum.getDesc());
                selectOptionVo.setValue(numberOfJobsEnum.getNumberOfJobs());
                result.add(selectOptionVo);
            }
            return ResultDto.ok(result);
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 新增
     *
     * @param coolTowerProjectAttendance
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDto add(CoolTowerProjectAttendance coolTowerProjectAttendance) {
        try {
            Date checkInDate = coolTowerProjectAttendance.getCheckInDate();
            Long coolTowerEmployeeId = coolTowerProjectAttendance.getCoolTowerEmployeeId();
            Long coolTowerProjectId = coolTowerProjectAttendance.getCoolTowerProjectId();
            // 判断cool_tower_employee_salary_project_relationship 表中是否存在关联关系
            boolean existData = coolTowerEmployeeSalaryProjectRelationshipService.isExistData(coolTowerEmployeeId, coolTowerProjectId);
            if (!existData) {
                // cool_tower_employee_salary_project_relationship 表中不存在关联关系，则向其中插入一条数据
                // 向 cool_tower_employee_salary_project_relationship 表中插入一条数据
                CoolTowerEmployee employee = coolTowerEmployeeService.getById(coolTowerEmployeeId);
                BigDecimal salary = BigDecimal.ZERO;
                if (employee != null) {
                    salary = employee.getSalary();
                }
                BigDecimal dailySettlementFee = BigDecimal.ZERO;

                if (employee != null) {
                    dailySettlementFee = employee.getDailySettlementFee();
                }
                BigDecimal subsidy = BigDecimal.ZERO;
                if (employee != null) {
                    subsidy = employee.getSubsidy();
                }
                coolTowerEmployeeSalaryProjectRelationshipService.insert(coolTowerEmployeeId, salary, dailySettlementFee, subsidy, coolTowerProjectId);
            }
            // 检查当前打卡是否重复打卡
            CoolTowerProjectAttendance isExists = baseMapper.selectByEmployeeIdAndProjectIdAndCheckInDate(coolTowerEmployeeId, coolTowerProjectId, checkInDate, null);
            if (isExists != null) {
                return ResultDto.fail("该员工已经打过卡了，无需重复打卡");
            }
            // 从cool_tower_employee_salary_project_relationship 表中获取员工在项目上的工数及各种费用
            CoolTowerEmployeeSalaryProjectRelationship employeeSalaryProjectRelationship = coolTowerEmployeeSalaryProjectRelationshipService.selectEmployeeSalaryProjectRelationship(coolTowerEmployeeId, coolTowerProjectId);
            // 向 cool_tower_project_attendance 表中插入一条数据
            BigDecimal dailySettlementFee = employeeSalaryProjectRelationship.getDailySettlementFee();
            if (dailySettlementFee == null) {
                dailySettlementFee = BigDecimal.ZERO;
            }
            BigDecimal numberOfJobs = coolTowerProjectAttendance.getNumberOfJobs();

            dailySettlementFee = dailySettlementFee.multiply(numberOfJobs);
            coolTowerProjectAttendance.setDailySettlementFee(dailySettlementFee);
            // 当日费用  = 日结费用+其他费用+补助
            BigDecimal dailyFee = BigDecimal.ZERO;
            dailyFee = dailyFee.add(dailySettlementFee);
            coolTowerProjectAttendance.setDailyFee(dailyFee);
            BigDecimal otherExpenses = coolTowerProjectAttendance.getOtherExpenses();
            if (otherExpenses == null) {
                otherExpenses = BigDecimal.ZERO;
            }
            dailyFee = dailyFee.add(otherExpenses);
            BigDecimal subsidy = employeeSalaryProjectRelationship.getSubsidy();
            coolTowerProjectAttendance.setSubsidy(subsidy);
            dailyFee = dailyFee.add(subsidy);
            coolTowerProjectAttendance.setDailyFee(dailyFee);
            boolean save = save(coolTowerProjectAttendance);
            return save ? ResultDto.ok() : ResultDto.fail();
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 根据项目ID统计这个项目的工数
     *
     * @param coolTowerProjectId
     */
    @Override
    public BigDecimal selectNumberOfJobsByCoolTowerProjectId(Long coolTowerProjectId) {
        BigDecimal result = BigDecimal.ZERO;
        try {
            result = baseMapper.selectNumberOfJobsByCoolTowerProjectId(coolTowerProjectId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 分页
     *
     * @param coolTowerProjectAttendance
     */
    @Override
    public ResultDto page(CoolTowerProjectAttendancePageDto coolTowerProjectAttendance) {
        try {
            IPage<CoolTowerProjectAttendance> page = new Page<>(coolTowerProjectAttendance.getCurrent(), coolTowerProjectAttendance.getSize());
            IPage<CoolTowerProjectAttendance> selectPage = baseMapper.page(page, coolTowerProjectAttendance);
            return ResultDto.ok(selectPage);
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 获取某个员工在项目的具体某一天的打卡信息
     *
     * @param coolTowerProjectAttendanceInfoDto
     */
    @Override
    public ResultDto coolTowerProjectAttendanceInfo(CoolTowerProjectAttendanceInfoDto coolTowerProjectAttendanceInfoDto) {
        try {
            CoolTowerProjectAttendance coolTowerProjectAttendance = baseMapper.coolTowerProjectAttendanceInfo(coolTowerProjectAttendanceInfoDto);
            return ResultDto.ok(coolTowerProjectAttendance);
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 修改某个员工在项目的某天打卡信息
     *
     * @param coolTowerProjectAttendance
     */
    @Override
    public ResultDto update(CoolTowerProjectAttendance coolTowerProjectAttendance) {
        try {
            // 查询当前打卡操作是否在数据库中已经存在数据
            Long coolTowerEmployeeId = coolTowerProjectAttendance.getCoolTowerEmployeeId();
            Long coolTowerProjectId = coolTowerProjectAttendance.getCoolTowerProjectId();
            Date checkInDate = coolTowerProjectAttendance.getCheckInDate();
            Long id = coolTowerProjectAttendance.getId();
            CoolTowerProjectAttendance isExists = baseMapper.selectByEmployeeIdAndProjectIdAndCheckInDate(coolTowerEmployeeId, coolTowerProjectId, checkInDate, id);
            if (isExists != null) {
                return ResultDto.fail("该员工已经打过卡了，无需重复打卡");
            }

            // 当日费用  = 日结费用+其他费用+补助
            BigDecimal dailyFee = BigDecimal.ZERO;
            //其他费用
            BigDecimal otherExpenses = coolTowerProjectAttendance.getOtherExpenses();
            if (otherExpenses == null) {
                otherExpenses = BigDecimal.ZERO;
            }
            dailyFee = dailyFee.add(otherExpenses);
            // 日结费用
            BigDecimal dailySettlementFee = coolTowerProjectAttendance.getDailySettlementFee();
            if (dailySettlementFee == null) {
                dailySettlementFee = BigDecimal.ZERO;
            }
            BigDecimal numberOfJobs = coolTowerProjectAttendance.getNumberOfJobs();
            if(numberOfJobs.equals(BigDecimal.ONE)){
                numberOfJobs = BigDecimal.TWO;
            }
            dailySettlementFee = dailySettlementFee.multiply(numberOfJobs);
            coolTowerProjectAttendance.setDailySettlementFee(dailySettlementFee);
            dailyFee = dailyFee.add(dailySettlementFee);
            // 补贴
            BigDecimal subsidy = coolTowerProjectAttendance.getSubsidy();
            if (subsidy == null) {
                subsidy = BigDecimal.ZERO;
            }
            dailyFee = dailyFee.add(subsidy);
            coolTowerProjectAttendance.setDailyFee(dailyFee);
            boolean update = updateById(coolTowerProjectAttendance);
            return update ? ResultDto.ok() : ResultDto.fail();
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 根据项目ID统计该项目的费用---点击填报时打开的页面中数据列表用的接口（分页）
     *
     * @param ipage
     * @param coolTowerProjectDto
     * @return
     */
    @Override
    public IPage<CostStatisticsVo> costStatistics(CoolTowerProjectDto coolTowerProjectDto) {
        try {
            IPage<CoolTowerProjectDto> page = new Page<>(coolTowerProjectDto.getCurrent(), coolTowerProjectDto.getSize());
            IPage<CostStatisticsVo> selectPage = baseMapper.costStatistics(page, coolTowerProjectDto);
            // 把每个人的备注放到CostStatisticsVo中
            Long projectId = coolTowerProjectDto.getId();
            List<CostStatisticsVo> records = selectPage.getRecords();
            if (CollectionUtils.isNotEmpty(records)) {
                for (CostStatisticsVo costStatisticsVo : records) {
                    Long coolTowerEmployeeId = costStatisticsVo.getCoolTowerEmployeeId();
                    List<String> selectRemark = selectRemark(projectId, coolTowerEmployeeId, null, null);
                    String remarks = selectRemark.toString().replace("[", "");
                    remarks = remarks.replace("]", "");
                    costStatisticsVo.setRemarks(remarks);
                }
            }
            return selectPage;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 快速打卡
     *
     * @param coolTowerEmployeeId
     */
    @Override
    public ResultDto quickCheckIn(CoolTowerProjectAttendance coolTowerProjectAttendance) {
        try {
            // 获取当前时间
            Date checkInDate = new Date();
            coolTowerProjectAttendance.setCheckInDate(checkInDate);
            // 查询当前打卡操作是否在数据库中已经存在数据
            Long coolTowerEmployeeId = coolTowerProjectAttendance.getCoolTowerEmployeeId();
            Long coolTowerProjectId = coolTowerProjectAttendance.getCoolTowerProjectId();
            CoolTowerProjectAttendance isExists = baseMapper.selectByEmployeeIdAndProjectIdAndCheckInDate(coolTowerEmployeeId, coolTowerProjectId, checkInDate, null);
            if (isExists != null) {
                return ResultDto.fail("该员工已经打过卡了，无需重复打卡");
            }
            coolTowerProjectAttendance.setNumberOfJobs(BigDecimal.ONE);
            coolTowerProjectAttendance.setRemark("快速打卡");
            CoolTowerEmployeeSalaryProjectRelationship employeeSalaryProjectRelationship = coolTowerEmployeeSalaryProjectRelationshipService.selectEmployeeSalaryProjectRelationship(coolTowerEmployeeId, coolTowerProjectId);
            if (employeeSalaryProjectRelationship != null) {
                BigDecimal otherExpenses = BigDecimal.ZERO;
                coolTowerProjectAttendance.setOtherExpenses(otherExpenses);
                BigDecimal subsidy = employeeSalaryProjectRelationship.getSubsidy();
                coolTowerProjectAttendance.setSubsidy(subsidy);
                BigDecimal dailySettlementFee = employeeSalaryProjectRelationship.getDailySettlementFee();
                coolTowerProjectAttendance.setDailySettlementFee(dailySettlementFee);
                BigDecimal dailyFee = BigDecimal.ZERO;
                if (subsidy != null) {
                    dailyFee = dailyFee.add(subsidy);
                }
                if (dailySettlementFee != null) {
                    dailyFee = dailyFee.add(dailySettlementFee);
                }
                dailyFee = dailyFee.add(otherExpenses);
                coolTowerProjectAttendance.setDailyFee(dailyFee);
            }
            boolean save = save(coolTowerProjectAttendance);
            return save ? ResultDto.ok() : ResultDto.fail();
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public ResultDto delete(Long id) {
        try {
            boolean delete = removeById(id);
            return delete ? ResultDto.ok() : ResultDto.fail();
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }
}




